package com.xiyou.luckdraw.web.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import tk.mybatis.spring.annotation.MapperScan;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * @ClassName: MybatisConfig
 * @Description:
 * @author: limingxing
 * @Date: 2019-10-15 21:17
 */
@Slf4j
public class MybatisConfig {

    /**
     * 第一个数据库 SqlSessionFactory && SqlSessionTemplate 创建
     */
    @Configuration
    @MapperScan(basePackages = {"com.xiyou.luckdraw.api.dal.mapper.luckdraw"},
            sqlSessionFactoryRef = "sqlSessionFactoryOne",
            sqlSessionTemplateRef = "sqlSessionTemplateOne")
    public static  class DBOne{
        @Resource
        DataSource dbOneDataSource;
        @Bean
        public SqlSessionFactory sqlSessionFactoryOne() throws Exception {
            log.info("sqlSessionFactoryOne 创建成功。");
            SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
            factoryBean.setDataSource(dbOneDataSource);
            factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/luckdraw/*.xml"));
            return factoryBean.getObject();
        }
        @Bean
        public SqlSessionTemplate sqlSessionTemplateOne() throws Exception {
            SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactoryOne()); // 使用上面配置的Factory
            return template;
        }
    }
    /**
     * 第二个数据库 SqlSessionFactory && SqlSessionTemplate 创建
     */
    @Configuration
    @MapperScan(basePackages = {"com.xiyou.luckdraw.api.dal.mapper.luckyelite"},
            sqlSessionFactoryRef = "sqlSessionFactoryTwo",
            sqlSessionTemplateRef ="sqlSessionTemplateTwo" )
    public static class DBTwo{
        @Resource
        DataSource dbTwoDataSource;
        @Bean
        public SqlSessionFactory sqlSessionFactoryTwo() throws Exception {
            log.info("sqlSessionFactoryTwo 创建成功。");
            SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
            factoryBean.setDataSource(dbTwoDataSource);

            factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/luckyelite/*.xml"));
            return factoryBean.getObject();
        }
        @Bean
        public SqlSessionTemplate sqlSessionTemplateTwo() throws Exception {
            SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactoryTwo()); // 使用上面配置的Factory
            return template;
        }
    }
}
